import router from './router'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { getToken } from '@/utils/auth' // 验权
import { Message } from 'element-ui'
const whiteList = ['/login', '/feedback/:from/:_id','/boon'] // 不重定向白名单
router.beforeEach((to, from, next) => {
    // 把url后面参数去掉，合并在访问事件中。。
    let params_len = Object.keys(to.params).length
    let path_str = to.fullPath
    let index = path_str.lastIndexOf("/");
    for (let i = 0; i < params_len; i++) {
        path_str = path_str.substring(0, index);
        index = path_str.lastIndexOf("/");
    }
    if (is_prod) {
        if (to.path) {
            // 线上去掉'SMS'
            let is_scfy = location.host == 'scfy.i3020.com' ? '' : '/sms';
            let name = to.fullPath == '/login' ? '未登录' : (JSON.parse(localStorage.getItem('USER_INFO')) ? JSON.parse(localStorage.getItem('USER_INFO')).nick : '未登录');
            _hmt.push(['_trackPageview', `${is_scfy}/#${path_str}`]);
            _hmt.push(['_trackEvent', name, '访问', `${to.meta.title}#${path_str}`]);
        }
    }
    NProgress.start()
    if (getToken()) {
        if (to.path === '/login') {
            next({ path: '/' })
        } else {
            next()
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1 || (whiteList.indexOf(to.matched[0].path) !== -1 && to.params.from == 3)) {//from==3 PC端 反馈页不用登录
            next()
        } else {
            if (from.fullPath == '/') {
                next('/login');
            } else {
                next('/login');
                Message({ message: '登录已失效，请重新登录', type: 'error'})
            }
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done() // 结束Progress
})